<?php

namespace App\Http\Controllers\Open;

use Illuminate\Bus\Batch;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Request as RequestFacade;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Validator;
use ZBrettonYe\Geetest\Geetest;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Bus;
use App\Jobs\ProcessDealLocation;
use App\Jobs\ProcessAddLocation;
use App\Models\GpsadvUsers;
use Throwable;
class LocationController extends Controller
{

    public function __construct(){
        Validator::extend('isvalidlatlong', function ($attribute, $value, $parameters, $validator) {
            if($attribute == "lotitude"){

                return $this->isValidLatLong("", $value);
            }elseif($attribute == "latitude"){

                return $this->isValidLatLong($value, "");
            }else{
                return false;
            }
        });
    }
    /**
     * 获取客户端传递的位置参数.
     */

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(\Illuminate\Http\Request $request)
    {
        $validator = [
            'client_id'=>'required|string|exists:gpsadv_users,user_client_id',
            "lotitude"=> "required|string|isvalidlatlong",
            "latitude"=> "required|string|isvalidlatlong"
        ];

        return Validator::make($request->all(), $validator, [
            'client_id.required' => trans('The client_id is required'),
            'lotitude.required' => trans('The lotitude is required'),
            'latitude.required' => trans('The latitude is required'),
            "client_id.exists"=>trans("The client_id is not exists"),
            "lotitude.isvalidlatlong"=>trans("The lotitude is not valided"),
            "latitude.isvalidlatlong"=>trans("The latitude is not valided")
        ]);
    }


    protected function isValidLatLong($lat, $long) {
        // 经度正则表达式
        $longitudeRegex = '/^[-]?((1[0-7][0-9])|([0-9]?[0-9]))[\.]\d{1,6}$/';
        // 纬度正则表达式
        $latitudeRegex = '/^[-]?(([0-8]?[0-9])|(90))[\.]\d{1,6}$/';
        // 检查经度是否在有效范围内
        if (preg_match($longitudeRegex, $long) === 1) {
            if ($long >= -180 && $long <= 180) {
                return true;
            }
        }

        // 检查纬度是否在有效范围内
        if (preg_match($latitudeRegex, $lat) === 1) {
            if ($lat >= -90 && $lat <= 90) {
                return true;
            }
        }

        return false;
    }
    //增加一个sign参数，添加时间戳和salt来验签,相同的签名的请求如果已经存在，则立即决绝
    public function sendPos(\Illuminate\Http\Request $request)
    {
        Log::info('sendPos: {input}', ['input' => $request->all()]);
        $validator = $this->validator($request);
        if ($validator->fails()) {
            $error_msg = $validator->errors()->first();
            return Response::returns([
                'errors' => 1,
                'message' => $error_msg
            ], 422);
        }
        $data = $request->all();
        $clientId=$data['client_id'];

        $client_phone = Redis::hget("client_id-android_id",$clientId);
        $data['android_id']=$client_phone;
        $batch =Bus::batch([
            new ProcessDealLocation($data),
            new ProcessAddLocation($data),
        ])->then(function (Batch $batch) {
            // 所有作业都已成功完成...
//            dump($batch);
            return Response::returns([
                'errors' => 0,
                'message' => "作业完成",
                'data'=>$batch->id
            ],200);
        })->catch(function (Throwable $e) {
            // 检测到第一个批处理作业失败...
            dump($e);
            // 链中的作业失败了...
//            dump($e);
//            return Response::returns([
//                'errors' => 1,
//                'message' => "作业异常".$e
//            ], 422);
        })->dispatch();

        return Response::returns([
            'errors' => 0,
            'message' => "作业完成",
            'data'=>$batch->id
        ],200);

    }
}
